package com.yy.micro.magic.core.loader.impl;

import com.yy.micro.magic.core.loader.ResourceLoader;
import com.yy.micro.magic.utils.JsonUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
 /**
   * @author YY
   * @version 1.0.0
   * @update 2021/9/22 9:27 下午
   * @description:静态资源加载抽象类，提供了加载文件的基本操作，子类只需要简单实现数据保存即可。
 */
public abstract class AbstractResourceLoader<T> implements ResourceLoader<T> {

    public static final String SCHEDULE_POSTFIX_JSON="*.json";
    public static final String SCHEDULE_BASE_PATH="schedules";

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void load() {
        String path = getResourcePath();
        String post = getResourcePost();
        Class<T> cls = getResourceClass();
        List<T> resources=load(path,post,cls);
        handle(resources);
    }

    protected void handle(List<T> resources){

    }

    protected Class<T> getResourceClass(){
        return null;
    }

    protected String getResourcePost(){
        return SCHEDULE_POSTFIX_JSON;
    }

    protected String getResourcePath(){
        return SCHEDULE_BASE_PATH;
    }

    @Override
    public List<T> load(final String path, String post, final Class<T> cls)  {
        String resourcePath = buildPath(path,post);
        List<T> list = new ArrayList<>();
        try {
            Resource[] resources =ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()).getResources(resourcePath);
            if (null != resources){
                for (Resource r:resources){
                    byte[] bytes = FileCopyUtils.copyToByteArray(r.getInputStream());
                    T t=JsonUtils.fromJson(new String(bytes, StandardCharsets.UTF_8),cls);
                    list.add(t);
                }
            }
        } catch (IOException e) {
            logger.warn("load resource"+resourcePath+" exception",e);
        }
        return list;
    }

    protected String buildPath(String path,String post){
        StringBuilder sb = new StringBuilder();
        if (!StringUtils.isEmpty(path)){
            sb.append(path);
        }
        if (!StringUtils.isEmpty(post)){
            if (sb.length()>0 && !path.endsWith("/") && !post.startsWith("/")){
                sb.append("/");
            }
            sb.append(post);
        }
        return "classpath:"+sb.toString();
    }
}
